<template>
	<view>
		<view
			v-if="!(empty && emptyNoShow)"
			:class="$style.pagination"
			@tap="load"
		>
			<template v-if="hasNext">
				<template v-if="loading">加载中...</template>
				<template v-else>点击加载更多</template>
			</template>
			<template v-else>
				<template>数据已加载完</template>
			</template>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { nextTick, ref } from 'vue'

const props = withDefaults(
	defineProps<{
		api: (params: any) => any,
        keyName? : string,
		pageSize: number,
		showLoading: boolean,
		emptyNoShow: boolean,
	}>(),
	{
		showLoading: true,
		pageSize: 15,
        keyName : 'id',
		emptyNoShow: false,
	}
)

const emit = defineEmits<{
	(e: 'finish', rows: any[], empty: boolean): void
}>()

const loading = ref(false)
const hasNext = ref(true)
const pageNo = ref(0)
const empty = ref(false)

async function load() {
	if (loading.value || !hasNext.value) return

	loading.value = true
    let params:any = { pageSize: props.pageSize }
    if(pageNo.value) {
        params.pageNo = pageNo.value
    }
	const res = await props.api(params)
	loading.value = false

	if (pageNo.value == 1 && (!res.data || res.data.length == 0)) {
		empty.value = true
	}

	if (!res.data || res.data.length < props.pageSize) {
		hasNext.value = false
	}

    if(res.data && res.data.length > 0) {
        pageNo.value = res.data[res.data.length - 1][props.keyName]
    }

	

	emit('finish', res.data || [], empty.value)
}

function reload() {
	empty.value = false
	pageNo.value = 1
	hasNext.value = true
	nextTick(() => {
		load()
	})
}

load()

defineExpose({
	load,
	reload,
})
</script>

<style module lang="scss">
.pagination {
	padding: 40px 0;
	text-align: center;
}
</style>
